const Controller = require('egg').Controller;
const sqlConfig = require('../util/sqlConfig')
const err = require('../util/err')
const moment = require('moment')
const util = require('../util/util')
const axios = require('axios')
const WX_SHOP_KEY = 'liuhu666liuhu666liuhu666liuhu666'
const parser = require("fast-xml-parser");  // join to xml
let j2xParser = parser.j2xParser
const X2JS = require('node-x2js');
const md5 = require('md5')
const qr = require('qr-image')

class UBusinessController extends Controller {
    //  商家类型一级分类
    async uType() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        if (r_body) {
            const data = await mysql.select('uType')
            const _data = JSON.parse(JSON.stringify(data))
            const uniqueData = util.uniqueArray(data, 'name')
            const returnData = []
            uniqueData.map(item => {
                const { name } = item
                const itm = _data.filter(item2 => item2.name === name)
                item.children = itm
                returnData.push({ ...item, children: [{ id: 0, name: '全部', subName: '全部', src: '' }, ...itm] })
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: returnData
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 商家二级分类
    async uSubType() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { name } = r_body
        const { mysql } = app
        if (r_body) {
            const data = await mysql.select('uType', {
                where: { name }
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: [{ id: 0, name: '全部', subName: '全部', src: '' }, ...data]
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 首页爆款推荐区商家信息
    async uTopBusiness() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { uSchoolId } = r_body
        const { mysql } = app
        if (r_body) {
            const topList = await mysql.select('uTop',{
                where:{
                    uSchoolId
                }
            })
            for (let index = 0; index < topList.length; index++) {
                const item = topList[index]
                const { id } = item
                const data = await mysql.query(sqlConfig.uBusinessList({ uSchoolId, topNum: id }))
                const _data = JSON.parse(JSON.stringify(data))
                topList[index].children = _data.filter(item => item.topNum > 0)
                // topList[index].top = _data.filter(item => item.topNum > 0)
            }
            const returnList = topList.filter(item=>item.children.length)
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: returnList
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 多条件查询商家家信息
    async uFilterBusiness() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        if (r_body) {
            

            // 距离排序下期开发
            // else if(filter==='longlat'){
            //     fil = {
            //         where: {uSchoolId,uType},
            //         orders: [['price','desc']], 
            //     }
            // }
            // function GetDistance(lat1,lng1,lat2,lng2){

            //     var radLat1 = Rad(lat1);
            //     var radLat2 = Rad(lat2);
            //     var a = radLat1 - radLat2;
            //     var  b = Rad(lng1) - Rad(lng2);
            //     var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
            //     Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
            //     s = s *6378.137 ;// EARTH_RADIUS;
            //     s = Math.round(s * 10000) / 10000; //输出为公里
            //     //s=s.toFixed(4);
            //     return s;
            // }

            //  await mysql.select('uBusiness', fil)
             let data =await mysql.query(sqlConfig.uFilterBusiness(r_body))
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: data
            }
        } else {
            ctx.body = err.err1
        }
    }
    //  商家详情
    async uBusinessDetail() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { uBusinessId } = r_body
        const { mysql } = app
        if (r_body) {
            let json
            let data = await mysql.select('uBusiness', {
                where: { id: uBusinessId }
            })
            if (data.length) {
                json = data[0]
                let data2 = await mysql.select('uTicket', {
                    where: { uBusinessId }
                })
                json.ticket = data2
                const data3 = await mysql.query(sqlConfig.getNum(uBusinessId))
                json.numOld = data3[0]['count(*)']
            } else {
                json = {}
            }

            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: json
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 用户下单
    async uAddOrder() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        if (r_body) {
            const { loginId, uTicketId, price, ticketNum, uSchoolId, openid, uBusinessId,userName,businessManageId } = r_body
            const orderNum = 'zn' + new Date().getTime()    //  15位时间戳
            const nowDate = new Date()
            const endDate = nowDate.getTime() + 5 * 60 * 1000
            const time = moment(nowDate).format('YYYY-MM-DD HH:mm:ss')
            const endTime = moment(endDate).format('YYYY-MM-DD HH:mm:ss')
            const params2 = {
                appid: 'wx069bb9fd47eb702b',
                mch_id: '1605857462',
                nonce_str: util.makeCode(30),
                body: 'u你校园支付',
                out_trade_no: orderNum,
                total_fee: '1',
                spbill_create_ip: '139.155.230.209',
                notify_url: 'https://api.zhongningwenhua.com/notifyUrl',
                trade_type: 'JSAPI',
                openid
            }
            let str = util.getWXSing(params2, WX_SHOP_KEY)
            params2.sign = str
            const j2xparser = new j2xParser();
            let obj = {
                xml: params2
            }
            const xml = j2xparser.parse(obj)
            let prepay_id = ''
            await axios.post('https://api.mch.weixin.qq.com/pay/unifiedorder', xml, {
                headers: {
                    "Content-Type": "application/xml"
                },
            }).then(function (res) {
                const rData = parser.parse(res.data)
                prepay_id = 'prepay_id=' + rData.xml.prepay_id
                console.log(prepay_id)
            }).catch(function (error) {
                ctx.body = err.err3(error)
            })
            const params = {
                loginId, uTicketId, orderNum, price, ticketNum, time, endTime, uSchoolId, prepay_id, uBusinessId,userName,businessManageId
            }
            await mysql.insert('uOrder', params)
            ctx.body = {
                code: 200,
                msg: '下单成功',
                data: {
                    orderNum
                }
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 根据订单号查询订单信息
    async uOrderInfo() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { orderNum } = r_body
        const { mysql } = app
        if (r_body) {
            let data = await mysql.select('uOrder', {
                where: { orderNum }
            })
            let json = {}
            if (data.length) {
                json = data[0]
                const { uTicketId } = json
                let data2 = await mysql.select('uTicket', {
                    where: { id: uTicketId }
                })
                json.ticketDetail = data2[0]
            }
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: json
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 支付
    async uPay() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { remark, uOrderId,businessManageId } = r_body
        const { mysql } = app
        if (r_body) {
            const ticketCode = `${util.makeCode(12)}bs${businessManageId}`
            await mysql.update('uOrder', {
                remark,
                status: 3,
                ticketCode
            }, {
                where: {
                    id: uOrderId
                }
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 接收信息
    async notifyUrl() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const query = ctx.query
        if (r_body) {
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 更新订单状态
    async uUpdateOrderStatus() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { uOrderId } = r_body
        const { mysql } = app
        if (r_body) {
            await mysql.update('uOrder', {
                status: 1,
            }, {
                where: {
                    id: uOrderId
                }
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 查询订单列表
    async uOrderList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { loginId, status } = r_body
        const { mysql } = app
        if (r_body) {
            let params
            if (status === 0) {
                params = {
                    loginId
                }
            } else {
                params = {
                    loginId,
                    status
                }
            }
            let data = await mysql.select('uOrder', {
                where: params,
                orders: [['id','desc']], 
            })
            for (let index = 0; index < data.length; index++) {
                const element = data[index]
                const { status, endTime, id } = element
                if (status === 1 && new Date(endTime).getTime() < new Date().getTime()) {
                    await mysql.update('uOrder', {
                        status: 2,
                    }, {
                        where: {
                            id
                        }
                    })
                }
                let data2 = await mysql.select('uTicket', {
                    where: { id: element.uTicketId }
                })
                element.ticketDetail = data2[0]
            }

            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: data
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 删除订单
    async uDeleteOrder() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { uOrderId } = r_body
        const { mysql } = app
        if (r_body) {
            await mysql.delete('uOrder', {
                id: uOrderId
            });
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 二维码生成
    async qrcode() {
        const { ctx, logger } = this;
        const { text } = ctx.query;
        var img = qr.image(text, { type: 'png', margin: 1, size: 10 });
        ctx.status = 200;
        ctx.type = 'image/png';
        ctx.body = img;
    }
    async ticketStatus() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const {ticketCode} = r_body
        if (r_body) {
            const data = await mysql.select('uOrder',{
                columns:['status'],
                where:{
                    ticketCode
                }
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: data.length?data[0]:{}
            }
        } else {
            ctx.body = err.err1
        }
    }
    
    

    // 1605857462   商户号id
    // const appid = 'wx069bb9fd47eb702b'
    // const appSecret = '9bb97baab7f3e893645262f0e5344a9b'
}



module.exports = UBusinessController;